package controllers;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import alipay.config.AlipayConfig;
import alipay.util.AlipayFunction;
import alipay.util.AlipayNotify;
import alipay.util.AlipayService;
import alipay.util.UtilDate;

import models.Indent;
import models.LendCard;
import models.MemType;
import models.Member;
import models.Rechargenotes;
import play.mvc.Controller;
import util.Util;

public class MemberView extends Controller  {

	//修改状态
	public static void updataindst(Long indid,Integer istate){
		System.out.println(istate+"----------------------------");
		int state = 0 ;
		try{
		Indent indent = Indent .findById(indid);
		indent.indsta = istate ;
		indent.save() ;
		state =  1 ;
		render(state);
		}catch(Exception e ){
			state = 0 ;
			e.printStackTrace();
			render(state);
		}
	}
	
	public static void member(){
		String userid = session.get("userid");
		System.out.println(userid +"-------------------------");
		if(userid == "" || userid == null){
			render("/proscenium/memlog.html");
		}
		Member meb=Member.findById(Long.parseLong(userid));
		if(meb == null){
			render("/proscenium/memlog.html");
		}
		MemType memtype = MemType.findById(Long.parseLong(meb.metid));
		LendCard lendcard = LendCard.find("from LendCard where lecnum = ? ", meb.lecnum).first();
		render("/proscenium/member.html",meb,memtype,lendcard);
	}
	
	public static void consume(){
		String userid = session.get("userid");
		Member meb=Member.findById(Long.parseLong(userid));
		if(meb == null){
			render("/proscenium/memlog.html");
		}
		MemType memtype = MemType.findById(Long.parseLong(meb.metid));
		LendCard lendcard = LendCard.find("from LendCard where lecnum = ? ", meb.lecnum).first();
		render("/proscenium/consume.html",meb,memtype,lendcard);
	}
	
	public static void recharge(){
		String userid = session.get("userid");
		Member meb=Member.findById(Long.parseLong(userid));
		if(meb == null){
			render("/proscenium/memlog.html");
		}
		MemType memtype = MemType.findById(Long.parseLong(meb.metid));
		LendCard lendcard = LendCard.find("from LendCard where lecnum = ? ", meb.lecnum).first();
		//List<Rechargenotes> reachlist = Rechargenotes.findAll();
		List<Rechargenotes> reachlist = Rechargenotes.find("from Rechargenotes order by rechtime desc ").fetch();
		render("/proscenium/recharge.html",meb,memtype,lendcard,reachlist);
	}
	
	public static void searchreache(String sdata,String edata){
		int state = 0 ;
		try{
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	        java.util.Date sdtime = format.parse(sdata);
	        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	        java.util.Date edtime = format1.parse(edata);
			if(sdata == "" && edata == ""){
				state = 2 ;
				render(state);
			}
			List<Rechargenotes> rlist = Rechargenotes.find("from Rechargenotes where  rechtime <= ?  and  rechtime >= ?", sdtime,edtime).fetch();
			System.out.println(rlist+"-----------------------------------------------------------------------------------------");
			state = 1 ;
			render("/MemberView/searchreache.html",rlist);
		}catch(Exception e){
			state = 0 ;
			e.printStackTrace();
			render(state);
		}
	}
	
	public static void log(){
		render("/proscenium/memlog.html");
	}
	
	public static void updatepwd(){
		String userid = session.get("userid");
		Member meb=Member.findById(Long.parseLong(userid));
		if(meb == null){
			render("/proscenium/memlog.html");
		}
		MemType memtype = MemType.findById(Long.parseLong(meb.metid));
		LendCard lendcard = LendCard.find("from LendCard where lecnum = ? ", meb.lecnum).first();
		render("/proscenium/upmbpwd.html",meb,memtype,lendcard);
	}
	
	public static void ckoldpwd(String oldpwd){
		int state = 0 ;
		try{
			Member member = Member.find("from Member where mempass = ?", Util.md5(oldpwd)).first();
			if(member != null){
				state = 1 ;
				render(state);
			}else{
				render(state);
			}
		}catch(Exception e){
				render(state);
			e.printStackTrace();
		}
	}
	
	public static void upsave(String newpass){
		int state = 0 ;
		try{
			String userid = session.get("userid");
			Member meb=Member.findById(Long.parseLong(userid));
			meb.mempass = Util.md5(newpass);
			meb.save();
			state = 1 ;
			render(state);
		}catch(Exception e){
			state = 0 ;
			render(state);
			e.printStackTrace();
		}
	}
	
	public static void disorder(){
		String userid = session.get("userid");
		Member meb=Member.findById(Long.parseLong(userid));
		if(meb == null){
			render("/proscenium/memlog.html");
		}
		MemType memtype = MemType.findById(Long.parseLong(meb.metid));
		LendCard lendcard = LendCard.find("from LendCard where lecnum = ? ", meb.lecnum).first();
		List<Indent> indentlist = Indent.find("from Indent where memid = ?", userid).fetch();
		render("/proscenium/order.html",meb,memtype,indentlist,lendcard);
	}
	
	public static void delorder(String orderid){
		int state = 0;
		try{
			int  result =  Indent.delete("from Indent where  id = ? ", orderid);
			if(result > 0){
				state = 1 ;
				render(state);
			}else{
				state = 0 ;
				render(state);
			}
		}catch(Exception e){
			state = 0 ;
			render(state);
			e.printStackTrace();
		}
	}
	
	public static void searchorder(String txtKey){
		System.out.println(txtKey+"-------------------------------");
		int state = 0 ;
		try{
			Indent indent = Indent.find("from Indent where indnum = ? ", txtKey).first();
			if(indent != null ){
				state = 1;
				render(indent);
			}else{
				render(state);
			}
		}catch(Exception e){
			render(state);
			e.printStackTrace();
		}
		
	}
	
	public static void imporder(){
		String userid = session.get("userid");
		Member meb=Member.findById(Long.parseLong(userid));
		if(meb == null){
			render("/proscenium/login.html");
		}
		MemType memtype = MemType.findById(Long.parseLong(meb.metid));
		System.out.println(memtype+meb.metid+"-------------+"+meb.lecnum+"+-----------------------------------------");
		LendCard lendcard = LendCard.find("from LendCard where lecnum = ? ", meb.lecnum).first();
		System.out.println(lendcard+"11--------------------------------------------");
		render("/proscenium/impresorder.html",meb,memtype);
	}
	
	public static void myborrow(){
		String userid = session.get("userid");
		Member meb=Member.findById(Long.parseLong(userid));
		if(meb == null){
			render("/proscenium/memlog.html");
		}
		MemType memtype = MemType.findById(Long.parseLong(meb.metid));
		System.out.println(memtype+meb.metid+"-------------+"+meb.lecnum+"+-----------------------------------------");
		LendCard lendcard = LendCard.find("from LendCard where lecnum = ? ", meb.lecnum).first();
		System.out.println(lendcard+"11--------------------------------------------");
		List<Indent> indentlist = Indent.find("from Indent where memid = ?", meb.id.toString()).fetch();
		
		render("/proscenium/myborrow.html",meb,memtype,indentlist);
	}
	
	public static void upmsg(){
		String userid = session.get("userid");
		Member meb=Member.findById(Long.parseLong(userid));
		if(meb == null){
			render("/proscenium/memlog.html");
		}
		MemType memtype = MemType.findById(Long.parseLong(meb.metid));
		System.out.println(memtype+meb.metid+"-------------+"+meb.lecnum+"+-----------------------------------------");
		LendCard lendcard = LendCard.find("from LendCard where lecnum = ? ", meb.lecnum).first();
		System.out.println(lendcard+"11--------------------------------------------");
		render("/proscenium/updatemsg.html",meb,memtype);
	}
	
	public static void upmsgsave(String memname,String mempoca,String mempho,String memtel,String memaddr,String memaddr2,String memaddr3,String memaddr4){
		int state = 0 ;
		try{
			String userid = session.get("userid");
			Member meb=Member.findById(Long.parseLong(userid));
			if(meb == null){
				render("/proscenium/memlog.html");
			}
			meb.memname = memname ;
			meb.mempoca = mempoca ;
			meb.mempho = mempho ;
			meb.memtel = memtel ;
			meb.memaddr = memaddr ;
			meb.memaddr2 = memaddr2 ;
			meb.memaddr3 = memaddr3 ;
			meb.memaddr4 = memaddr4 ;
			meb.save();
			state = 1 ;
			render(state);
		}catch(Exception e){
			state = 0 ;
			render(state);
			e.printStackTrace();
		}
		
	}
	
	public static void trss(){
		String userid = session.get("userid");
		Member meb=Member.findById(Long.parseLong(userid));
		if(meb == null){
			render("/proscenium/memlog.html");
		}
		MemType memtype = MemType.findById(Long.parseLong(meb.metid));
		System.out.println(memtype+meb.metid+"-------------+"+meb.lecnum+"+-----------------------------------------");
		LendCard lendcard = LendCard.find("from LendCard where lecnum = ? ", meb.lecnum).first();
		System.out.println(lendcard+"11--------------------------------------------");
		render("/proscenium/tailormaderss.html",meb,memtype);
	}
	
	public static void login(String uname,String upwd){
		int state = 0;
		try{
			Member member = Member.find("from Member where (memnum = ? or mememail = ?) and mempass = ? ", uname,uname,Util.md5(upwd)).first();
			if(member != null){
				state = 1;
				session.put("userid", member.id);
				render(state);
			}else{
				render(state);
			}
		}catch(Exception e){
			render(state);
		}
	}
	
	public static void logout(){
		session.remove("userid");
		System.out.println(Util.uuid()+"------------------------------------------------------ff---------------------------");
		String script = "window.location='/index.html'";
		render("/501.html",script);
	}
	
	//支付页面
	public static void paymoney(){
		String userid = session.get("userid");
		Member meb=Member.findById(Long.parseLong(userid));
		if(meb == null){
			render("/proscenium/memlog.html");
		}
		MemType memtype = MemType.findById(Long.parseLong(meb.metid));
		LendCard lendcard = LendCard.find("from LendCard where lecnum = ? ", meb.lecnum).first();
		String show_url = AlipayConfig.show_url;
		String mainname = AlipayConfig.mainname;
		render("/proscenium/rechargemoney.html",show_url,mainname,meb,memtype,lendcard);
	}
	
	//充值
	public static void rechmoney(String alimoney,String pay_bank){
		int state = 0;
		try{
		//request.setCharacterEncoding("UTF-8");
		//AlipyConfig.java中配置信息（不可以修改）
		String input_charset = AlipayConfig.input_charset;
		String sign_type = AlipayConfig.sign_type;
		String seller_email = AlipayConfig.seller_email;
		String partner = AlipayConfig.partner;
		String key = AlipayConfig.key;

		String show_url = AlipayConfig.show_url;
		String notify_url = AlipayConfig.notify_url;
		String return_url = AlipayConfig.return_url;
		
		///////////////////////////////////////////////////////////////////////////////////
		
		//以下参数是需要通过下单时的订单数据传入进来获得
		//必填参数
		UtilDate date = new UtilDate();//调取支付宝工具类生成订单号
		        String out_trade_no = date.getOrderNum();//请与贵网站订单系统中的唯一订单号匹配
		        //订单名称，显示在支付宝收银台里的“商品名称”里，显示在支付宝的交易管理的“商品名称”的列表里。
		        String subject = "微微书香";
		        //订单描述、订单详细、订单备注，显示在支付宝收银台里的“商品描述”里
		        String body = "在线充值";
		        //订单总金额，显示在支付宝收银台里的“应付总额”里
		        String total_fee = alimoney;
		        
		        //扩展功能参数——默认支付方式
		        String pay_mode = pay_bank;
		        String paymethod = "";		//默认支付方式，四个值可选：bankPay(网银); cartoon(卡通); directPay(余额); CASH(网点支付)
		        String defaultbank = "";	//默认网银代号，代号列表见http://club.alipay.com/read.php?tid=8681379
		        if(pay_mode.equals("directPay")){
		        	paymethod = "directPay";
		        }
		        else{
		        	paymethod = "bankPay";
		        	defaultbank = pay_mode;
		        }
		        
		        //扩展功能参数——防钓鱼
		        //请慎重选择是否开启防钓鱼功能
		//exter_invoke_ip、anti_phishing_key一旦被设置过，那么它们就会成为必填参数
		//开启防钓鱼功能后，服务器、本机电脑必须支持远程XML解析，请配置好该环境。
		//建议使用POST方式请求数据
		        String anti_phishing_key  = "";				//防钓鱼时间戳
		        String exter_invoke_ip= "";					//获取客户端的IP地址，建议：编写获取客户端IP地址的程序
		        //如：
		        //anti_phishing_key = AlipayFunction.query_timestamp(partner);	//获取防钓鱼时间戳函数
		        //exter_invoke_ip = "202.1.1.1";
		        
		        //扩展功能参数——其他
		        String extra_common_param = "";				//自定义参数，可存放任何内容（除=、&等特殊字符外），不会显示在页面上
		        String buyer_email = "";					//默认买家支付宝账号
		        
		        //扩展功能参数——分润(若要使用，请按照注释要求的格式赋值)
		        String royalty_type = "";					//提成类型，该值为固定值：10，不需要修改
		        String royalty_parameters ="";
		//提成信息集，与需要结合商户网站自身情况动态获取每笔交易的各分润收款账号、各分润金额、各分润说明。最多只能设置10条
		//各分润金额的总和须小于等于total_fee
		//提成信息集格式为：收款方Email_1^金额1^备注1|收款方Email_2^金额2^备注2
		//如：
		//royalty_type = "10"
		//royalty_parameters	= "111@126.com^0.01^分润备注一|222@126.com^0.01^分润备注二"

		        /////////////////////////////////////////////////////////////////////////////////////////////////////

		//构造函数，生成请求URL
		        
		        System.err.println(partner);
		        System.err.println(seller_email);
		        System.err.println(return_url);
		        System.err.println(notify_url);
		        System.err.println(show_url);
		        System.err.println(out_trade_no);
		        System.err.println(alimoney);
		        
		        String sHtmlText = AlipayService.BuildForm(partner,seller_email,return_url,notify_url,show_url,out_trade_no,
		subject,body,total_fee,paymethod,defaultbank,anti_phishing_key,exter_invoke_ip,extra_common_param,buyer_email,
		royalty_type,royalty_parameters,input_charset,key,sign_type);
//		        state = 1 ;
//		        String str = "";
//		        str+="[{$}"+state+"{$}]"+sHtmlText;
		        System.out.println("---------------------------------------------------------------------------------------");
		        String[] str = new String[1];
		        str[0]  = sHtmlText;
		        
		    	SimpleDateFormat   formatter   =   new   SimpleDateFormat   ("yyyy-MM-dd hh:mm:ss");   
				Date   curDate   =   new   Date(System.currentTimeMillis());//获取当前时间   
				String  starttime   =   formatter.format(curDate);
				
		        //记录充值记录
		        Rechargenotes recharg = new Rechargenotes(); 
		        
		        recharg.rechmoney = Double.parseDouble(alimoney);
		        recharg.rechstyle = pay_bank;
		        recharg.rechsate = 0 ;
		        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		        java.util.Date dtime = format.parse(starttime);
		        recharg.rechtime = dtime;
		        recharg.remark = "";
		        recharg.save();
		        System.out.println("-------------------------------------------------------------------------------------");
		        render("/Payment/alipayto.html",str,alimoney,out_trade_no);
		}catch(Exception e ){
			state = 0;
			e.printStackTrace();
		}      
	}
	
	public static void notify_url(Map requestParams,String notify_id,String sign,String trade_no,String out_trade_no,String total_fee,String subject,String body,String buyer_email,String trade_status){
		String key = AlipayConfig.key;
		//获取支付宝POST过来反馈信息
		Map params = new HashMap();
		Map requestParam = requestParams;
		for (Iterator iter = requestParam.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParam.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
		valueStr = (i == values.length - 1) ? valueStr + values[i]
		: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "UTF-8");
			params.put(name, valueStr);
		}
		
		//判断responsetTxt是否为ture，生成的签名结果mysign与获得的签名结果sign是否一致
		//responsetTxt的结果不是true，与服务器设置问题、合作身份者ID、notify_id一分钟失效有关
		//mysign与sign不等，与安全校验码、请求时的参数格式（如：带自定义参数等）、编码格式有关
		String mysign = AlipayNotify.GetMysign(params,key);
		String responseTxt = AlipayNotify.Verify(notify_id);
		String sign1 = sign ;
		
		//写日志记录（若要调试，请取消下面两行注释）
		String sWord = "responseTxt=" + responseTxt + "\n notify_url_log:sign=" + sign + "&mysign=" + mysign + "\n notify回来的参数：" + AlipayFunction.CreateLinkString(params);
		AlipayFunction.LogResult(sWord);
		
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		String trade_n = trade_no;				//支付宝交易号
		String order_no = out_trade_no;	        //获取订单号
		String total_fee1 = total_fee ;	        //获取总金额
		String subject0 = new String(subject);//商品名称、订单名称
		String body1 = "";
		if(body != null){
			body1 = new String(body);//商品描述、订单备注、描述
		}
		String buyer_email1 = buyer_email;		//买家支付宝账号
		String trade_status1 = trade_status;		//交易状态
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
		
		if(mysign.equals(sign1) && responseTxt.equals("true")){//验证成功
			//////////////////////////////////////////////////////////////////////////////////////////
			//请在这里加上商户的业务逻辑程序代码

			//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
			
			if(trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")){
		//判断该笔订单是否在商户网站中已经做过处理（可参考“集成教程”中“3.4返回数据处理”）
			//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
			//如果有做过处理，不执行商户的业务程序
				renderText("success");
				//out.println("success");	//请不要修改或删除
			} else {
				renderText("success");
				//out.println("success");	//请不要修改或删除
			}
			//——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

			//////////////////////////////////////////////////////////////////////////////////////////
		}else{//验证失败
			//out.println("fail");
			renderText("fail");
		}
	}
	
	public static void return_url (Map requestParams,String notify_id,String sign,String trade_no,String out_trade_no,String total_fee,String subject,String body,String buyer_email,String trade_status){
		String key = AlipayConfig.key;
		//获取支付宝GET过来反馈信息
		Map params = new HashMap();
		Map requestParam = requestParams;
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
		valueStr = (i == values.length - 1) ? valueStr + values[i]
				: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			valueStr = new String(valueStr);
			params.put(name, valueStr);
		}
		
		//判断responsetTxt是否为ture，生成的签名结果mysign与获得的签名结果sign是否一致
		//responsetTxt的结果不是true，与服务器设置问题、合作身份者ID、notify_id一分钟失效有关
		//mysign与sign不等，与安全校验码、请求时的参数格式（如：带自定义参数等）、编码格式有关
		String mysign = AlipayNotify.GetMysign(params,key);
		String responseTxt = AlipayNotify.Verify(notify_id);
		String sign1 = sign;
		
		//写日志记录（若要调试，请取消下面两行注释）
		//String sWord = "responseTxt=" + responseTxt + "\n return_url_log:sign=" + sign + "&mysign=" + mysign + "\n return回来的参数：" + AlipayFunction.CreateLinkString(params);
		//AlipayFunction.LogResult(sWord);
		
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		String trade_n = trade_no;				//支付宝交易号
		String order_no = out_trade_no;	        //获取订单号
		String total_fee1 = total_fee;	        //获取总金额
		String subject1 = new String(subject);//商品名称、订单名称
		String body1 = "";
		if( body != null){
			body1 = new String(body);//商品描述、订单备注、描述
		}
		String buyer_email1 = buyer_email;		//买家支付宝账号
		String trade_status1 = trade_status;		//交易状态
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
			
		String verifyStatus = "";
		
		if(mysign.equals(sign1) && responseTxt.equals("true")){
			//////////////////////////////////////////////////////////////////////////////////////////
			//请在这里加上商户的业务逻辑程序代码

			//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
			if(trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")){
		//判断该笔订单是否在商户网站中已经做过处理（可参考“集成教程”中“3.4返回数据处理”）
			//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
			//如果有做过处理，不执行商户的业务程序
			}
			verifyStatus = "验证成功";
			member();
			//——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

			//////////////////////////////////////////////////////////////////////////////////////////
		}else{
			verifyStatus = "验证失败";
		}
	}
}
